<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/23 0023
 * Time: 下午 5:32
 */

namespace App\Process;

use App\Parser\OnClose;
use App\Service\PlatService;
use App\Service\PlatsService;
use EasySwoole\Config;
use EasySwoole\Core\Component\Logger;
use EasySwoole\Core\Swoole\Process\AbstractProcess;
use EasySwoole\Core\Swoole\ServerManager;
use Swoole\Process;

class Heartbeat extends AbstractProcess
{
    public function run(Process $process)
    {
        $heartbeat_check_interval = Config::getInstance()->getConf('MAIN_SERVER.SETTING.heartbeat_check_interval');  //心跳检测时间
        //TODO 被COCOS 修改为固定.
        $heartBeatTime = 10 * 1000;
        Logger::getInstance()->log('---------------Proce-Start----------'.$this->getProcessName() ,'heartbeat');
        $this->addTick(intval($heartBeatTime), function () {
            try {
                Logger::getInstance()->console('【' . $this->getProcessName() . '】Start send...');
                $startFd = 0;
                while (true){
                    //所有FD用户
                    $fds = ServerManager::getInstance()->getServer()->connection_list($startFd, 10);
                    if ($fds===false or count($fds) == 0) {
                        echo $this->getProcessName() ." => finish\n";
                        break;
                    };
                    $startFd = end($fds);
                    Logger::getInstance() ->log ('startFd:' . $startFd, 'heartbeat');
                    $logInfo = isset($fds) && $fds ? json_encode($fds) : '';
                    $fdsCount = isset($fds) && $fds ? count($fds) : 0;
                    Logger::getInstance() -> log('total fds:' . $fdsCount . '==>' . $logInfo, 'heartbeat');

                    if (!$fds) return false;

                    foreach ($fds as $k => $fd) {
                        Logger::getInstance()->log('HeartBeat Send Data:' . $fd . '==> 检测心跳数据；发送====PONG', 'heartbeat');
                        $result = ServerManager::getInstance()->getServer()->push($fd, "PONG");
                        Logger::getInstance()->log('HeartBeat Send Result:' . $fd . '==>' . json_encode($result), 'heartbeat');
                        if ($result) continue;
                        //如果发送失败，说明链接被关闭了，清理
                        Logger::getInstance()->log('Check Current FD is Closed , FD = '.$fd, 'heartbeat');
                        /* $pushData = PlatService::getPushData($fd);
                        Logger::getInstance()->log('Plat Data:'.$pushData, 'heartbeat');
                        if (!$pushData) continue;
                        $pushData = json_decode($pushData, true);
                        $platCode = isset($pushData['pc']) && $pushData['pc'] ? $pushData['pc'] : '';
                        $pushType = isset($pushData['pt']) && $pushData['pt'] ? $pushData['pt'] : '';
                        $userToken = isset($pushData['ut']) && $pushData['ut'] ? $pushData['ut'] : '';
                        if (!$platCode || !$pushType || !$userToken) continue;
                        //调用关闭方法清理无效的Fd
                        $close = new OnClose($fd);
                        $close->destroy(); */
                    }
                    Logger::getInstance()->log('---------------heartbeat-end----------------', 'heartbeat');
                }
                return true;
            } catch (\Throwable $e) {
                //print_r($e->getMessage());
                //Logger::getInstance()->log('---------------heartbeat-err-start----------------');
                Logger::getInstance()->log($e->getMessage(),'heartbeat');
                //Logger::getInstance()->log('---------------heartbeat-err-end----------------');
                return false;
            }
        });
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }
}